
using System;
using System.Collections.Generic;
using System.Linq;
using MonoTouch.Foundation;
using MonoTouch.UIKit;
using System.Linq;

namespace ComBrowser
{
	public partial class SearchViewController : UIViewController
	{
		#region Constructors

		// The IntPtr and initWithCoder constructors are required for controllers that need 
		// to be able to be created from a xib rather than from managed code

		public SearchViewController (IntPtr handle) : base(handle)
		{
			Initialize ();
		}

		[Export("initWithCoder:")]
		public SearchViewController (NSCoder coder) : base(coder)
		{
			Initialize ();
		}

		public SearchViewController () : base("SearchViewController", null)
		{
			Initialize ();
		}

		MainViewController ctrlParent;
		public SearchViewController (MainViewController CtrlParent)
		{
			this.ctrlParent = CtrlParent;
		}
		
		void Initialize ()
		{
		}
		
		#endregion
		
		
		public string Query=null;
		public int Scope=0;
		
		public override void ViewDidLoad ()
		{
			txtSearch.Delegate = new SearchDelegate (this);
			tblResults.Source = new DataSource (this);

			txtSearch.ShowsCancelButton = true;
			this.View.BackgroundColor = UIColor.GroupTableViewBackgroundColor;
			txtSearch.BecomeFirstResponder ();
			segSearchWhat.TouchUpInside += delegate { this.Scope = segSearchWhat.SelectedSegment; };

		}
		
		public Dictionary<SearchResultSection, List<Commentary>> data = new Dictionary<SearchResultSection, List<Commentary>> ();
		public Dictionary<SearchResultSection, List<Commentary>> Data {
			get { return data; }
			set {
				data = value;
			//	combinedCommentariesData = null;
				tblResults.ReloadData ();
			}
		}
		
 //todo array teh section data for better speed and add a nonhtmlbody to the data
		
		public void HideSearch ()
		{
			ctrlParent.HideSearch ();	
		}

		#region SearchDelegate
		
		class SearchDelegate : UISearchBarDelegate {
			ComDomain comDomain=null;
			SearchViewController controller;
			public SearchDelegate (SearchViewController CtrlParent)
			{
				controller = CtrlParent;
				comDomain = ComDomain.Instance ();
			}
			public override void SearchButtonClicked (UISearchBar bar)
			{
				bar.ResignFirstResponder ();
				controller.Query = bar.Text;
				controller.Data = comDomain.Search (controller.Scope, controller.Query);
			}
	
			public override void CancelButtonClicked (UISearchBar bar)
			{
				bar.ResignFirstResponder ();
				this.controller.HideSearch ();
			}
		}
		#endregion
		
		#region UITableViewSource
		class DataSource : UITableViewSource
		{
			SearchViewController controller;
			private Dictionary<int, SearchCellViewController> controllers = null;

			public DataSource (SearchViewController controller)
			{
				this.controller = controller;
			}

			public override int NumberOfSections (UITableView tableView)
			{
				return controller.Data.Count;
			}

			// Customize the number of rows in the table view
			public override int RowsInSection (UITableView tableview, int section)
			{
				
				SearchResultSection s = controller.Data.Keys.Where (e => e.Index == section).First ();
				return s.ResultCount;
			}

			 public override string TitleForHeader (UITableView tableView, int section)
			 {
			 	SearchResultSection s = controller.Data.Keys.Where (e => e.Index == section).First ();
			 	return s.Title;
			 }

			

			
			public override float GetHeightForRow (UITableView tableView, NSIndexPath indexPath)
			{
				return 100f;
			}


			// Customize the appearance of table view cells.
			public override UITableViewCell GetCell (UITableView tableView, MonoTouch.Foundation.NSIndexPath indexPath)
			{
				UITableViewCell cell = tableView.DequeueReusableCell ("readingCell");
				SearchCellViewController cellController = null;
				
				if (cell == null) {
					cellController = new SearchCellViewController ();
					NSBundle.MainBundle.LoadNib ("SearchCellViewController", cellController, null);
					cell = cellController.Cell;
					cell.Tag = Environment.TickCount;
					cell.TextLabel.BackgroundColor = UIColor.Clear;
					cell.Opaque = false;
		
					try {
						controllers.Add (cell.Tag, cellController);
					} catch (Exception) {
					}
				} else {
					cellController = controllers[cell.Tag];
				}
 
				SearchResultSection section = controller.Data.Keys.Where (e => e.Index == indexPath.Section).First ();
				cellController.SetCommentaryToDisplay (controller.Data[section][indexPath.Row], controller.Query);
				return cell;
			}

			/*
			// Override to support conditional editing of the table view.
			public override bool CanEditRow (UITableView tableView, MonoTouch.Foundation.NSIndexPath indexPath)
			{
				// Return false if you do not want the specified item to be editable.
				return true;
			}
			*/
			/*
			// Override to support editing the table view.
			public override void CommitEditingStyle (UITableView tableView, UITableViewCellEditingStyle editingStyle, MonoTouch.Foundation.NSIndexPath indexPath)
			{
				if (editingStyle == UITableViewCellEditingStyle.Delete) {
					controller.TableView.DeleteRows (new NSIndexPath[] { indexPath }, UITableViewRowAnimation.Fade);
				} else if (editingStyle == UITableViewCellEditingStyle.Insert) {
					// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view.
				}
			}
			*/
			/*
			// Override to support rearranging the table view.
			public override void MoveRow (UITableView tableView, NSIndexPath sourceIndexPath, NSIndexPath destinationIndexPath)
			{
			}
			*/
			/*
			// Override to support conditional rearranging of the table view.
			public override bool CanMoveRow (UITableView tableView, NSIndexPath indexPath)
			{
				// Return false if you do not want the item to be re-orderable.
				return true;
			}
			*/

			// Override to support row selection in the table view.
			public override void RowSelected (UITableView tableView, MonoTouch.Foundation.NSIndexPath indexPath)
			{
				// Navigation logic may go here -- for example, create and push another view controller.
				//var c = new ContentWebViewController (controller.NewsArticles[indexPath.Row]);
				//controller.NavigationController.PushViewController (c, true);
			}
		}
		
		
		
		#endregion
		
		
	}
}
